# routes_shop.py
from flask import Blueprint, render_template, request, redirect, url_for, jsonify, flash, current_app
from flask_login import login_required, current_user
from app.extensions import db
from app.models import Order, OrderItem, Product
from app.utils.orders_utils import calc_amount_cents, gen_order_no
from datetime import datetime
from flask_babel import _

shop_bp = Blueprint('shop', __name__, url_prefix='/shop')

@shop_bp.route('/checkout/confirm', methods=['GET', 'POST'])
@login_required
def checkout_confirm():
    """
    确认订单页面：
    GET: 展示单个商品 + 收件信息表单
    POST: 创建订单 + 订单项，跳转支付页
    """
    pid = request.values.get('pid', type=int)
    qty = request.values.get('qty', type=int) or 1

    product = Product.query.get_or_404(pid)

    # ★ 起订量
    min_qty = getattr(product, "min_order_qty", 1) or 1
    if qty < min_qty:
        qty = min_qty  # 方案一：自动拉到起订量

        # 数量最少 1
    if qty <= 0:
        qty = min_qty

    if product.stock is not None and product.stock < min_qty:
        flash(_("当前库存不足以达到起订量，无法下单"), "warning")
        return redirect(url_for("front.product_detail", pid=product.id))

    # 再做一次库存校验，避免直接构造 URL 超卖
    if getattr(product, "stock", None) is not None and product.stock < qty:
        flash(_('库存不足'), 'warning')
        return redirect(url_for('front.product_detail', slug=product.slug or product.id))

    if request.method == 'GET':
        # 从当前用户信息里准备“默认收件人信息”
        default_recipient = {
            "name": current_user.recipient_name or current_user.username,
            "email": current_user.email,
            "phone": current_user.phone or "",
            "address": current_user.shipping_address or "",
            "postal_code": current_user.postal_code or "",
        }

        # POST 之后金额计算用修正后的 qty
        unit_price_cents = product.price or 0
        amount_cents = unit_price_cents * qty
        display_amount = amount_cents / 100  # 分 -> 元
        # 展示确认信息页
        return render_template(
            'checkout_confirm.html',
            p=product,
            qty=qty,
            user=current_user,
            recipient=default_recipient,  # ★ 传给模板回显用
            amount_cents=amount_cents,
            display_amount=display_amount
        )

    # POST: 提交订单
    # 你可以改成 WTForm，这里先用简单版 request.form
    recipient_name = request.form.get('recipient_name') or current_user.recipient_name or current_user.username
    recipient_email = request.form.get('recipient_email') or current_user.email
    recipient_phone = request.form.get('recipient_phone') or current_user.phone or ""
    recipient_address = request.form.get('recipient_address') or current_user.shipping_address or ""
    recipient_postal_code = request.form.get('recipient_postal_code') or current_user.postal_code or ""
    remark = request.form.get('remark') or ''

    current_user.recipient_name = recipient_name
    current_user.phone = recipient_phone
    current_user.postal_code = recipient_postal_code
    current_user.shipping_address = recipient_address

    unit_price_cents = product.price or 0

    amount_cents = unit_price_cents * qty

    # 创建订单
    order = Order(
        user_id=current_user.id,
        order_no=gen_order_no(),
        amount=amount_cents,
        currency='USD',   # 看你的项目，可能是 product.currency
        status='pending',
        product_id=product.id,   # 为了后面减库存方便
        recipient_name=recipient_name,
        recipient_email=recipient_email,
        recipient_phone=recipient_phone,
        recipient_address=recipient_address,
        recipient_postal_code=recipient_postal_code,
        remark=remark,
    )
    db.session.add(order)
    db.session.flush()  # 拿到 order.id

    # 创建订单项（单商品）
    item = OrderItem(
        order_id=order.id,
        title=product.title,
        sku=getattr(product, 'sku', None),
        qty=qty,
        unit_price=unit_price_cents,
    )
    db.session.add(item)
    if getattr(product, "stock", None) is not None:
        product.stock -= qty
    db.session.commit()

    # 跳转到支付页面
    return redirect(url_for('shop.pay', order_id=order.id))


@shop_bp.route('/pay/<int:order_id>', methods=['GET'])
@login_required
def pay(order_id):
    """
    付款页面：渲染 PayPal 按钮（前端会调用 create/capture 接口）
    """
    order = Order.query.filter_by(id=order_id, user_id=current_user.id).first_or_404()
    if order.status != 'pending':
        # 已支付/取消时回订单详情
        return redirect(url_for('shop.order_detail', order_no=order.order_no or f'#{order.id}'))

    display_amount = (order.amount or 0) / 100  # 分 -> 元
    paypal_client_id = current_app.config.get('PAYPAL_CLIENT_ID', '')
    currency = order.currency or 'USD'

    return render_template(
        'pay.html',
        order=order,
        display_amount=display_amount,
        paypal_client_id=paypal_client_id,
        currency=currency,
    )


@shop_bp.route('/orders/<order_no>')
@login_required
def order_detail(order_no):
    """
    订单详情页
    """
    order = Order.query.filter_by(order_no=order_no, user_id=current_user.id).first_or_404()
    items = OrderItem.query.filter_by(order_id=order.id).all()
    return render_template('order_detail.html', order=order, items=items)